package com.homework.controller;

import com.homework.pojo.Article;
import com.homework.repository.CommentRepository;
import jdk.jfr.Frequency;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class indexController {

    @Autowired
    private CommentRepository commentRepository;

    @RequestMapping("/home")
    public ModelAndView home(ModelAndView modelAndView, @RequestParam(value = "page",defaultValue = "0") Integer page,
                             @RequestParam(value = "size",defaultValue = "2") Integer size){
        Pageable pageable = PageRequest.of(page,size, Sort.by(Sort.Direction.DESC,"id"));
        Page<Article> articlePage = commentRepository.findAll(pageable);
        List<Article> articles = articlePage.getContent();
        modelAndView.addObject("list",articles);
        Integer total = articlePage.getTotalPages();
        Integer totalPage = total % size > 0 ? total / size + 1 : total / size;
        modelAndView.addObject("first",0);
        modelAndView.addObject("prev",page > 0 ? page - 1 : page);
        modelAndView.addObject("next",page < totalPage ? page + 1 : totalPage);
        modelAndView.addObject("end",totalPage);
        modelAndView.setViewName("client/index");
        return modelAndView;
    }

    @RequestMapping("/admin")
    public ModelAndView admin(ModelAndView modelAndView){
        modelAndView.setViewName("client/admin");
        return modelAndView;
    }
}
